package request

import (
	"errors"
	"oa-system/pkg/utils"
	"strconv"
	"strings"
)

// UserListRequest 用户列表请求参数
type UserListRequest struct {
	PageRequest
	DepartmentID *uint  `form:"departmentID"`
	Email        string `form:"email"`
	Name         string `form:"name"`
	RoleIDs      []uint `form:"-"` // 使用自定义绑定
	RolesStr     string `form:"roles"`
}

// CreateUserRequest 创建用户请求
type CreateUserRequest struct {
	Name  string `json:"name" binding:"required"`
	Email string `json:"email" binding:"required,email"`
	// Password     string `json:"password" binding:"required,min=6"`
	Phone        string `json:"phone" binding:"required,len=11"`
	DepartmentID *uint  `json:"department_id"`
	RoleIDs      []uint `json:"role_ids"`
}

// UpdateUserRequest 更新用户请求
type UpdateUserRequest struct {
	Name         string `json:"name" binding:"required"`
	Email        string `json:"email" binding:"required,email"`
	Password     string `json:"password" binding:"omitempty,min=6"`
	Phone        string `json:"phone" binding:"required,len=11"`
	DepartmentID *uint  `json:"department_id"`
	RoleIDs      []uint `json:"role_ids"`
}

// LoginRequest 登录请求
type LoginRequest struct {
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required"`
}

// Validate 验证并处理请求参数
func (r *UserListRequest) Validate() error {
	// 处理基础分页参数
	r.ProcessPageRequest()

	// 处理角色ID
	if r.RolesStr != "" {
		r.RoleIDs = make([]uint, 0)
		for _, idStr := range strings.Split(r.RolesStr, ",") {
			if id, err := strconv.ParseUint(idStr, 10, 32); err == nil {
				r.RoleIDs = append(r.RoleIDs, uint(id))
			}
		}
	}

	return nil
}

// Validate 验证创建用户请求
func (r *CreateUserRequest) Validate() error {
	if r.Name == "" {
		return errors.New("用户名不能为空")
	}
	if !utils.IsValidEmail(r.Email) {
		return errors.New("邮箱格式不正确")
	}
	// if len(r.Password) < 6 {
	// 	return errors.New("密码长度不能小于6位")
	// }
	return nil
}

func (r *LoginRequest) Validate() error {
	if !utils.IsValidEmail(r.Email) {
		return errors.New("邮箱格式不正确")
	}
	if len(r.Password) < 6 {
		return errors.New("密码长度不能小于6位")
	}
	return nil
}
